const router = require('koa-router')();
// const apiRequest = require('../common/apiRequest');
const submitFeed = require('../../app/mws/feeds/SubmitFeed');
const mwsReorder = require('pt-core-common/ptCore').util.mwsReorder;
const feedsProductTemplate = require('../../app/model/feeds.templates.product.func');
const feedsProductImageTemplate = require('../../app/model/feeds.templates.productImage.func');
const feedsRelationshipsTemplate = require('../../app/model/feeds.templates.relationships.func');
const feedsOverridesTemplate = require('../../app/model/feeds.templates.overrides.func');
const feedsPriceTemplate = require('../../app/model/feeds.templates.price.func');
const feedsInventoryTemplate = require('../../app/model/feeds.templates.inventory.func');

router.prefix('/api/v1/feeds');

router.get('/', function (ctx, next) {
    ctx.body = 'this is a users response!'
});

/***********************
 *  feed product api (excel feeding)
 ************************/
router.post('/submissions/products/:marketplaceid/', async (ctx, next) =>{
    let sellerId = ctx.headers.sellerid;
    let mwsAuthToken = ctx.headers.mwsauthtoken;

    let marketplaceid = ctx.params.marketplaceid;
    let feedType = "_POST_FLAT_FILE_LISTINGS_DATA_"; // "_POST_PRODUCT_DATA_";

    const product = ctx.request.body;
    const product_type = product.product_type;
    const item_type = product.item_type;
    const template_name = `product_${item_type}`;
    // let feedContent = feedsProductTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", [product]);
    // feedContent = mwsReorder(feedContent);
    const obj2excel = require('../../app/util/obj2excel');
    const xlsx_buffer = await obj2excel(template_name, product);

    try {
        let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, xlsx_buffer, [marketplaceid]);
        console.log(json);
        ctx.response.status = 200;
        ctx.response.body = {
            data: json,
        };
    } catch (error) {
        ctx.response.status = 500;
        ctx.response.body = {
            data: error,
        };
    }
});

/***********************
 *  feed inventory api (excel feeding)
 ************************/
router.post('/submissions/inventory/:marketplaceid', async (ctx, next) => {
  let sellerId = ctx.headers.sellerid;
  let mwsAuthToken = ctx.headers.mwsauthtoken;

  let marketplaceid = ctx.params.marketplaceid;
  let feedType = "_POST_FLAT_FILE_INVLOADER_DATA_"; // "_POST_INVENTORY_AVAILABILITY_DATA_";  // ref: http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html

  let inventory = ctx.request.body;
  const template_name = "priceinventory";

  // const feedContent = feedsInventoryTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", [inventory]);
  const obj2excel = require('../../app/util/obj2excel');
  const xlsx_buffer = await obj2excel(template_name, inventory);
  try {
    let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, xlsx_buffer, [marketplaceid]);
    ctx.response.status = 200;
    ctx.response.body = {
      data: json,
    };
  } catch (error) {
    ctx.response.status = 500;
    ctx.response.body = {
      data: error,
    };
  }
});

/***********************
 *  feed product image api
 ************************/
router.post('/productImages/:marketplaceid/:productid', async (ctx, next) => {
    let sellerId = ctx.headers.sellerid;
    let mwsAuthToken = ctx.headers.mwsauthtoken;

    let marketplaceid = ctx.params.marketplaceid;
    let productid = ctx.params.productid;

    let feedType = "_POST_PRODUCT_IMAGE_DATA_";

    // TODO: 如下要替换成远程调用 pt-core-products 服务
    // const Prodcut_dao = require('../admproducts/functions/admproducts.mongo.func');
    // const product = await Prodcut_dao.get_ImageById$(productid);
    // const product_images = product.product_image;
    const productImages = await apiRequest("");

    const feedContent = feedsProductImageTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", "KOS-LS-ROSEWATER-parent", productImages);

    try {
        let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, feedContent, [marketplaceid]);
        ctx.response.status = 200;
        ctx.response.body = {
            data: json,
        };
    } catch (error) {
        ctx.response.status = 500;
        ctx.response.body = {
            data: error,
        };
    }
});

/***********************
 *  feed relationships api
 ************************/
router.post('/submissions/relationships/:marketplaceid', async (ctx, next) => {
    let sellerId = ctx.headers.sellerid;
    let mwsAuthToken = ctx.headers.mwsauthtoken;

    let marketplaceid = ctx.params.marketplaceid;
    let feedType = "_POST_PRODUCT_RELATIONSHIP_DATA_";  // ref: http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html
    let relationships = ctx.request.body;

    const feedContent = feedsRelationshipsTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", [relationships]);

    try {
        let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, feedContent, [marketplaceid]);
        ctx.response.status = 200;
        ctx.response.body = {
            data: json,
        };
    } catch (error) {
        ctx.response.status = 500;
        ctx.response.body = {
            data: error,
        };
    }
});

/***********************
 *  feed overrides api
 ************************/
router.post('/overrides/:marketplaceid', async (ctx, next) => {
    let sellerId = ctx.headers.sellerid;
    let mwsAuthToken = ctx.headers.mwsauthtoken;

    let marketplaceid = ctx.params.marketplaceid;
    let feedType = "_POST_PRODUCT_OVERRIDES_DATA_";  // ref: http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html
    let overrides = ctx.request.body;

    const feedContent = feedsOverridesTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", [overrides]);
    try {
        let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, feedContent, [marketplaceid]);
        ctx.response.status = 200;
        ctx.response.body = {
            data: json,
        };
    } catch (error) {
        ctx.response.status = 500;
        ctx.response.body = {
            data: error,
        };
    }
});

/***********************
 *  feed price api
 ************************/
router.post('/price/:marketplaceid', async (ctx, next) =>{
    let sellerId = ctx.headers.sellerid;
    let mwsAuthToken = ctx.headers.mwsauthtoken;

    let marketplaceid = ctx.params.marketplaceid;
    let feedType = "_POST_PRODUCT_PRICING_DATA_";  // ref: http://docs.developer.amazonservices.com/en_US/feeds/Feeds_FeedType.html
    let price = ctx.request.body;

    const feedContent = feedsPriceTemplate.amazonEnvelopeTemplate2xml(sellerId, "Update", [price]);
    try {
        let json = await submitFeed.submitFeed(sellerId, mwsAuthToken, feedType, feedContent, [marketplaceid]);
        ctx.response.status = 200;
        ctx.response.body = {
            data: json,
        };
    } catch (error) {
        ctx.response.status = 500;
        ctx.response.body = {
            data: error,
        };
    }
});



/***********************
 *  general feeds api, require specify feedtype
 *  feedtype:
 _POST_PRODUCT_DATA_ (product),
 _POST_PRODUCT_IMAGE_DATA_ (productImage)
 ************************/
// router.post('/general/:marketplaceid/:feedtype', async function(req, res, next) {
//     let sellerId = req.headers.sellerid;
//     let mwsAuthToken = req.headers.mwsauthtoken;
//
//     let marketplaceid = req.params.marketplaceid;
//     let feedType = req.params.feedtype;
//
//     let tmp = req.body;
//     let feedContent = json2xml("AmazonEnvelope", tmp);
//     let json = xml2json(feedContent);
//     let json_text = JSON.stringify(json);
//     let submitFeed = require('../../../public/mws/feed/SubmitFeed');
//     try {
//         let json = await submitFeed(sellerId, mwsAuthToken, feedType, feedContent, [marketplaceid]);
//         console.log(json);
//         return res.json(json);
//     } catch (error) {
//         console.error(error);
//         return res.status(500).json(error);
//     }
// });

module.exports = router;
